<?php
namespace app\model;

use think\Model;
// use Firebase\JWT\JWT;
// use Firebase\JWT\Key;
// use think\cache\driver\Redis;
// use think\facade\Cache;
use think\facade\Db;

class CategoryModel extends Model
{

    protected $pk = 'id';
    // 设置当前模型对应的完整数据表名称
    protected $table = 'sh_category';


    public static function single( $category_id ){

        $sql = "select * from sh_category where id='" . $category_id . "'";
        // return pdo_fetch( $sql );
        return Db::query( $sql )[0];
    }

    public static function hasChildCategory( $parent_id ){

        
        $sql = 'select * from sh_category where parent_id= ' . $parent_id;
        
        // return pdo_fetch( $sql );
        return Db::query( $sql );
    }

    public static function remove( $cat_id ){


        $sql = 'delete from sh_category where id =' . $cat_id;

        // return pdo_query( $sql );
        return Db::query( $sql );

    }


    public static function remove_category_path( $category_id ){

        $sql = 'delete from sh_category_path where category_id="' . $category_id .'"';

        // return pdo_fetch( $sql );
        return Db::query( $sql );
    }

    public static function set_category_path( $category_id, $parent_id ){

        // global $_W;
        $uniacid = current_uni_account();
        $path_list = self::get_category_path( $parent_id );

        $level = 0;
        foreach( $path_list as $path ){
            $sql = 'INSERT INTO sh_category_path SET category_id = "' . $category_id
                . '",path_id = "' . $path['path_id']
                . '",uniacid = "' . $uniacid
                . '",`level` = "' . $path['level']
                . '" ';
            Db::execute( $sql );
            $level ++;
        }

        $level ++;
        $sql = 'INSERT INTO sh_category_path SET category_id = "' . $category_id
            . '",path_id = "' . $category_id
            . '",uniacid = "' . $uniacid
            . '",`level` = "' . $level
            . '" ';

        Db::execute( $sql );
    }

    public static function get_category_path( $category_id ){

        $sql = 'SELECT * FROM sh_category_path cp
                inner join sh_category c on cp.path_id = c.id
                WHERE cp.category_id="' . $category_id . '" order by `level` ';

        // return pdo_fetchall( $sql );
        return Db::query( $sql );
    }

    public static function get_path_list( $filter = [] ){

        // global $_W;
        $where_arr = [];
        $uniacid = current_uni_account();
        $where_arr[] = ' c.uniacid=' . $uniacid;
        if( !empty($filter['name']) ){
            $where_arr[] = ' c.name like "%' . $filter['name'] . '%"';
        }

        if( isset($filter['status']) ){
            $where_arr[] = ' c.status = "' . $filter['status'] . '"';
        }

        if( !empty($filter['category_ids']) ){
            $category_ids = join( ',', $filter['category_ids'] );
            $where_arr[] = ' c.id in (' . $category_ids . ')';
        }

        $where_str = '';
        if( !empty( $where_arr ) ){
            $where_str = ' where ' . join(' and ', $where_arr );
        }

        $sql = 'SELECT 
            c.*,
            GROUP_CONCAT(
                cc.`name` 
                ORDER BY cp.`level` ASC SEPARATOR \'>\'
            ) AS cat_name 
            FROM
            sh_category c 
            LEFT JOIN sh_category_path cp 
                ON c.`id` = cp.`category_id` 
            LEFT JOIN sh_category cc 
                ON cp.`path_id` = cc.`id` 
                ' . $where_str . '
            GROUP BY c.`id` 
            ORDER BY c.sort_order, c.id ASC,
            cp.`level` DESC';

        return Db::query( $sql );

    }

    public static function edit( $category_id, $data ){

        $sql = "UPDATE  sh_category  SET
                  `name` = '" . $data['name'] . "',
                  sort_order = " . $data['sort_order'] . ",
                  `status` = " . $data['status'] . ",
                  parent_id = " . $data['parent_id'] . ", 
                  image = '" . $data['image'] . "' 
                WHERE id = '" . $category_id . "'";

        return Db::execute( $sql );

    }

    public static function createOne( $data ){

        // global $_W;
        // $sql = "insert into  sh_category  SET
        //           `uniacid` = '" . $_W['uniacid'] . "',
        //           `name` = '" . $data['name'] . "',
        //           sort_order = " . $data['sort_order'] . ",
        //           `status` = " . $data['status'] . ",
        //           `image` = '" . $data['image'] . "',
        //           parent_id = " . $data['parent_id'] ;

        
        $insertData = [
            'uniacid'       => current_uni_account(),
            'name'          => $data['name'],
            'sort_order'    => $data['sort_order'],
            'status'        => $data['status'],
            'image'         => $data['image'],
            'parent_id'     => $data['parent_id'],
        ];

        return Db::name('sh_category')->insertGetId( $insertData );
    }


    public static function tree( ){

        // global $_W;
        $uniacid = current_uni_account();
        $sql = "SELECT 
                  c.*,
                  GROUP_CONCAT(cp.path_id 
                    ORDER BY cp.`level` ASC) AS path,
                  MAX(cp.`level`) AS cat_level 
                FROM
                  sh_category_path cp 
                  LEFT JOIN sh_category c 
                    ON cp.`category_id` = c.id 
                WHERE c.status = 1 and cp.uniacid=" . $uniacid . "
                GROUP BY cp.category_id ";

        // $cats = pdo_fetchall( $sql );
        $cats = Db::query( $sql );
        $tree = [];

        foreach( $cats as $cat ){

            $path_arr = explode(',',$cat['path'] );

            self::setChild( $tree, $path_arr, $cat );

        }

        return $tree;

    }

    public static function setChild( &$jiedian, $path, $cat ){

        $cat_id = array_shift( $path );

        if( !empty( $jiedian[ $cat_id ] ) ){

            if( empty( $jiedian[ $cat_id ]['children'] ) ){

                $jiedian[ $cat_id ]['children'] = [];

            }

            self::setChild( $jiedian[ $cat_id ]['children'], $path, $cat );

        }else if( $cat_id == $cat['id'] ){

            $jiedian[ $cat_id ] = $cat;

        }


    }

    
    public static function tree2( ){

        $uniacid = current_uni_account();
        $category_list = self::where( 'parent_id' , 0 )
                    ->where( 'uniacid' , $uniacid )
                    ->select();

        foreach( $category_list as $category ){

            self::getChildren( $category );
        }
        return $category_list;
    }

    public static function getChildren( &$parent ){
        $category_list = self::where( 'parent_id' , $parent->id )->select();
        foreach( $category_list as &$category ){
            self::getChildren( $category );

        }
        $parent['children'] = $category_list;
    }
}